from flask import Flask, render_template, request, redirect, url_for, jsonify, flash
import uuid

# 初始化Flask应用
app = Flask(__name__, template_folder='.')
app.secret_key = 'your_secret_key'  # 用于闪现消息

# 内存中的日志事项列表
logs = []

# 主页路由
@app.route('/')
def index():
    return render_template('index.html', logs=logs)

# 添加日志
@app.route('/add_log', methods=['POST'])
def add_log():
    title = request.form.get('title')
    description = request.form.get('description')
    completed = 'completed' in request.form

    if not title or not description:
        return jsonify({'error': '请填写所有必填字段！'}), 400

    log = {
        'id': str(uuid.uuid4()),  # 使用UUID作为唯一的ID
        'title': title,
        'description': description,
        'completed': completed
    }

    logs.append(log)
    return jsonify({'message': '日志已成功添加！', 'log': log}), 201

# 删除日志
@app.route('/delete_log/<log_id>', methods=['POST'])
def delete_log(log_id):
    global logs
    logs = [log for log in logs if log['id'] != log_id]
    return jsonify({'message': '日志已成功删除！'}), 200

# 编辑日志
@app.route('/edit_log/<log_id>', methods=['GET', 'POST'])
def edit_log(log_id):
    log = next((log for log in logs if log['id'] == log_id), None)
    if not log:
        return jsonify({'error': '日志不存在！'}), 404

    if request.method == 'POST':
        title = request.form.get('title')
        description = request.form.get('description')
        completed = 'completed' in request.form

        if not title or not description:
            return jsonify({'error': '请填写所有必填字段！'}), 400

        log['title'] = title
        log['description'] = description
        log['completed'] = completed
        return jsonify({'message': '日志已成功更新！', 'log': log}), 200

    # 返回日志数据以供编辑
    return jsonify(log), 200

# 切换完成状态
@app.route('/toggle_complete/<log_id>', methods=['POST'])
def toggle_complete(log_id):
    log = next((log for log in logs if log['id'] == log_id), None)
    if log:
        log['completed'] = not log['completed']
        return jsonify({'completed': log['completed']}), 200
    else:
        return jsonify({'error': '日志不存在'}), 404

# 启动应用
if __name__ == '__main__':
    app.run(debug=True)